import styled from 'styled-components';
import React, { useState, useEffect } from 'react';

import { ProChat } from '@ant-design/pro-chat';

import { useLayoutContext } from '../../api';
import { SqliteSettings, peerAssistantChat } from 'services';

export interface ChatPageProps {

}

export const ChatPage: React.FC<ChatPageProps> = (props) => {

    const [result, setResult] = useState<any>();

    const [_peerId, homePath] = useLayoutContext();

    const [settingService, setSettingService] = useState<SqliteSettings>(new SqliteSettings(`${homePath}/rrg01.sqlite`));

    const [provider, setProvider] = useState<{ provider: string, [key: string]: any } | null>(null);

    useEffect(() => {
        settingService.getValueByCategory("ai_settings", "default_setting", '').then((vstr) => {
            if (vstr == '') {
                return;
            }
            console.log(vstr);
            let obj = JSON.parse(vstr);
            setProvider(obj);
        });
    }, []);

    if (provider == null || !provider) {
        return (
            <EmptyContainer data-tauri-drag-region>
                没有加载或设置大模型，请到设置中进行设置！
            </EmptyContainer>
        );
    }

    return (
        <Container>
            <Header data-tauri-drag-region></Header>
            <ChatContainer>
                <ProChat
                    style={{
                        height: '100%',
                        backgroundColor: '#FFF'
                    }}
                    showTitle
                    userMeta={{
                        avatar: '🚀',
                        title: `我`,
                    }}
                    assistantMeta={{ avatar: '🚀', title: '助理', backgroundColor: '#67dedd' }}
                    request={async (messages) => {
                        let result = await peerAssistantChat(messages.map((message, index) => {
                            return {
                                content: [{
                                    type: 'text',
                                    text: message.content + '',
                                }],
                                role: message.role,
                            };
                        }), {
                            provider: {
                                version: 'OpenAIChat',
                                url: `${provider.baseUrl}/v1/chat/completions`,
                                token_key: 'Authorization',
                                token: `Bearer ${provider.apikey}`,
                                options: {}
                            },
                            model: `${provider.model}`,
                            prompt_enhance: false
                        });
                        console.log(result);
                        return new Response(result.map((msg: any, index: number) => {
                            if (!msg.content) {
                                return '';
                            }
                            return msg.content.map((content: any, cindex: number) => {
                                if (content.type === 'text') {
                                    return content.text;
                                } else if (content.type === 'image_url') {
                                    return content.url;
                                } else {
                                    return content;
                                }
                            }).join('\n');
                        }).join('\n'));
                    }}
                />
            </ChatContainer>
        </Container>
    );
}

const Container = styled.div`
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    background-color: #fff;
`;


const EmptyContainer = styled.div`
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
`;

const Header = styled.div`
    width: 100%;
    height: 30px;
`;

const ChatContainer = styled.div`
    flex:1;
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    background-color: #fff;
`;